'''
The Python language.
'''

import re

from . import _base, _lang

NAME = "Python"

# Version numbers to check for.
MIN_MAJOR_VERSION = 2
MAX_MAJOR_VERSION = 3
MAX_MINOR_VERSION = 9

class PythonEnvironment(_base.Environment):
    
    # I am currently uninterested in exposing the Python interpreter's 
    # command-line arguments.
    has_arguments = False
    
    def __init__(self, host, path, version):
        self.language = _lang.Python
        self.host = host
        self.path = path
        self.version = version
                        
def check_using_exec(host, path, description, environment_list):
    py = host.popen([path, '--version'])
    stdoutdata, stderrdata = py.communicate()
    all_data = stdoutdata + stderrdata
    m = re.match(r'Python ([0-9.]+)', all_data)
    if m:
        version = m.group(1)
        environment_list[_lang.Python.name][description].append(PythonEnvironment(host, path, version))

def check_using_glob(host, path, description, environment_list):
    """
    Checks a path glob (wildcard) for Python executables, and adds any found
    to environment_list.
    """
    exe_list = host.glob(path)
    exe_list.sort()
    for exe in exe_list:
        check_using_exec(host, exe, description, environment_list)

def check_using_which(host, path, description, environment_list):
    """
	Checks $PATH for Python executables by calling which(1), and adds any found
	to environment_list.
	"""
    which = host.popen(['which', path])
    which.wait()
    if which.returncode == 0:
        check_using_exec(host, path, description, environment_list)

def configure(host_list, environment_list):
    """
    Configures this language by checking each host in host_list and adding
    detected environments to environment_list.  (Same for all auto-loading
    configure methods.)
    """
    for host in host_list:
        if 'nt' in host.os_name_list:
            check_using_glob(host, r'c:\Python*\python.exe', 
                             'Python for Windows', environment_list)
            check_using_glob(host, r'c:\cygwin\bin\python*.exe', 
                             'Python (Cygwin)', environment_list)
        else:
            for major in range(MIN_MAJOR_VERSION, MAX_MAJOR_VERSION + 1):
                for minor in range(0, MAX_MINOR_VERSION + 1):
                    check_using_which(host, 'python%i.%i' % (major, minor),
                                      'Python', environment_list)
